package cn.stylefeng.guns.modular.tasks;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.stylefeng.guns.core.timer.TimerTaskRunner;
import cn.stylefeng.guns.modular.entity.Seat;
import cn.stylefeng.guns.modular.service.SeatService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 每天批量增加有效座位预约情况到redis缓存
 *
 * @author 李宝嘉
 * @Date 2022/1/23 16:52
 */
@Component
public class BatchAddSeatRedisTaskRunner implements TimerTaskRunner {
    public static final String INIT_BIt = "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SeatService seatService;

    @Override
    public void action() {
        DateTime today = DateTime.now();
        LambdaQueryWrapper<Seat> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Seat::getId).eq(Seat::isCanReserved, true);
        List<Seat> seatList = seatService.lambdaQuery().select(Seat::getId).eq(Seat::isCanReserved, true).list();
        String todayStr = DateUtil.format(today, "MM-dd");
        long expireUnixTime = DateUtil.beginOfDay(DateUtil.tomorrow()).toCalendar().getTimeInMillis();
        stringRedisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection stringRedisConn = (StringRedisConnection) connection;
            seatList.forEach(seat -> {
                String key = "seatId:" + todayStr + seat.getId().toString();
                stringRedisConn.set(key, INIT_BIt);
                stringRedisConn.expireAt(key, expireUnixTime);
            });
            return null;
        });
    }
}
